import { useState, useEffect, useRef } from "react";
import Slideshow from "../../components/Slideshow";
import Text_Carousel from "../../components/Text_Carousel";
import Presentation from "../../components/Presentation";
import FloatingBall from "../../components/FloatingBall";
import Position from "../../components/Position";
import Item from "./components/Item";
import { useSelector, useDispatch } from "react-redux";
import "@/css/Home.less";
import instance from "../utils/https";
import { Toast } from "antd-mobile";
import { List, PullRefresh } from "react-vant";
import { setHomePageP_id } from "../../store/modules/data";
import {config} from '../../components/Share'
import { useNavigate } from "react-router-dom";

// import {setUserInfo} from '../../store/modules/data'
// import SupportContestant from "./page/SupportContestant";

interface Activity {
  _id: string;
  accumulatedNum: number;
  announcement: string;
  endTime: string;
  isStart: boolean;
  joinNum: number;
  rule: string;
  startTime: string;
  title: string;
  visitNum: number;
  __v: number;
}

export default function Home() {
  const select = ["最热", "排行", "最新"];
  const [active, setActive] = useState(select[0]);
  const [searchval, setSearchval] = useState("");
  const [list, setList] = useState<any[]>([]);
  const [activityList, setActivityList] = useState<Activity | null>(null);
  const [count, setCount] = useState(0);
  const [loading, setLoading] = useState(false);
  // const [isOpen, setIsOpen] = useState(false);
  // const [id,setId] = useState('')
  const loadMoreRef = useRef(true);
  const pageRef = useRef(1);
  const user_id = localStorage.getItem("_id");
  let homePageP_id = useSelector((state: any) => state.homePageP_id);
  const dispatch = useDispatch();

  // const getCode = () => {
  //   const appId = "wxc84327f9bba81aff";

  //   const code = getUrlParam('code')
  
  //   const redirectUri = encodeURIComponent(window.location.href); // 替换为你的回调地址
  
  //   if (!code) {
  
  //     window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=snsapi_userinfo&state=234#wechat_redirect`;
  
  //   } else {
  
  //     getOpenId(code);
  
  //   }
  
  // };
  
  // const getUrlParam = (name: string) => {
  //   alert(window.location.search)
  //   const urlParams = new URLSearchParams(window.location.search);
  
  //   return urlParams.get(name);
  
  // };
  
  // const getOpenId = (code: string) => {
  
  //   instance.get('/api/wechat-login', { params: { code } })
  
  //     .then((response) => {
  
  //       const userInfo = response.data;
  
  //       console.log('用户信息:', userInfo);
  
  //       // Toast.success('登录成功！');
  
  //       // 在这里处理用户信息，比如存储到 Redux 或本地存储
  
  //       localStorage.setItem('userInfo', JSON.stringify(userInfo));
  
  //       dispatch(setUserInfo(userInfo));
  
  //     })
  
  //     .catch((error) => {
  
  //       console.error('登录失败:', error);
  
  //       Toast.show('登录失败，请重试！');
  
  //     })
  
  // };
  
  // useEffect(() => {
  
  //   getCode();
  
  // }, []);


  const getData = async (reset = false, actives = active) => {
    if (loading) return;
    setLoading(true);

    if (reset) {
      setList([]);
      pageRef.current = 1;
    }

    // console.log(homePageP_id,'123');

    if(homePageP_id === 1){
      homePageP_id = ""
    }

    
    try {
      const res: any = await instance.get("/homePage/getaplyuser", {
        params: {
          nowPage: pageRef.current,
          positionid: homePageP_id,
          searchcontent: searchval,
          fsc: actives,
        },
      });

      if (pageRef.current === 1) {
        setList(res.users);
      } else {
        setList((prev: any) => [...prev, ...res.users]);
      }

      setCount(res.userstotal);
      loadMoreRef.current = res.users.length >= 6;
    } catch (error) {
      console.error("获取用户数据失败", error);
    } finally {
      setLoading(false);
    }
  };

  const getActivityInfo = async () => {
    try {
      const res: any = await instance.get("/homePage/getVisit");
      setActivityList(res.data || null); // 假设只使用第一个活动
    } catch (error) {
      console.error("获取活动信息失败", error);
    }
  };
  const navigate = useNavigate()
  const handleVote = async (id: string) => {
    // setId(id)
    const token = localStorage.getItem("token");
    if (!token) {
      Toast.show({
        content: "请先登录",
      });
      setTimeout(() =>{
        navigate('/app/login')
      },1500)
      return;
    }
    try {
      const res: any = await instance.post("/homePage/udvote", {
        voter_id: user_id,
        candidate_ids: [id],
        vtime: Date.now(),
      });
      if (res) {
        // setIsOpen(false)
        Toast.show({
          content: `已投${res.totalVotes}票，今日可投剩余${res.remainingVotes}票`,
        });

        resetPagination();
        getData(true);
      }
    } catch (error: any) {
      
      // if(error.response?.data?.message === "每天只能投十次"){
        // setIsOpen(true)
        // <SupportContestant cid={id} onClose={(isOpen2: boolean) => setIsOpen(isOpen2)}></SupportContestant>
      // }
      Toast.show({
        content: "每天只能投十票",
      })
    }
  };

  const resetPagination = () => {
    setList([]);
    pageRef.current = 1;
    loadMoreRef.current = true;
  };

  const handleSearchOrSortChange = () => {
    resetPagination();
    getData(true);
  };

  const onRefresh = (showToast = true) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        if (showToast) {
          Toast.show({ content: "刷新成功" });
        }
        resetPagination();
        setActive("最热");
        setSearchval("");
        getData(true);
        resolve(true);
      }, 1000);
    });
  };

  useEffect(() => {
    if (homePageP_id) {
      resetPagination();
      getData(true);
    }
  }, [homePageP_id]);

  useEffect(() => {
    getData(true);
    getActivityInfo();
    config()
  }, []);

  // 当activityList变化时，强制重新渲染
  useEffect(() => {
    if (activityList) {
      console.log("活动信息已加载", activityList);
    }
  }, [activityList]); // 监听activityList的变化

  return (
    <PullRefresh
      onRefresh={() => onRefresh(true)}
      onRefreshEnd={() => console.log("onRefreshEnd")}
    >
      <div className="home">
        {/* 如果activityList为null，加载中状态 */}
        <Text_Carousel activityList={activityList} />
        <Slideshow />
        <FloatingBall />

        <div className="content">
          <p className="title">{`《调味大师${activityList?.title}》`}</p>
          <Presentation activityList={activityList} />
          
          <div className="rank">
            {select.map((item, index) => (
              <p
                key={index}
                className={active === item ? "active" : ""}
                onClick={() => {
                  setActive(item);
                  resetPagination();
                  getData(true, item);
                }}
              >
                {item}
              </p>
            ))}
          </div>

          <Position
            pId={homePageP_id}
            setPId={(id: any) => dispatch(setHomePageP_id(id))}
          />

          <div className="search">
            <input
              type="text"
              value={searchval}
              onChange={(e) => setSearchval(e.target.value)}
              placeholder="请输入选手名称、编号"
            />
            <button onClick={handleSearchOrSortChange}>搜索</button>
          </div>

          {searchval && (
            <p className="searchval">
              搜索关键词 “{searchval}”{" "}
              <span onClick={() => setSearchval("")}>取消搜索</span>
            </p>
          )}

          <List
            offset={0}
            className="list"
            finished={!loadMoreRef.current || list.length >= count}
            finishedText="没有更多了"
            onLoad={async () => {
              if (loadMoreRef.current && !loading) {
                pageRef.current += 1;
                await getData();
              }
            }}
          >
            {list.map((item, index) => (
              <Item key={index} Item={item} Change={handleVote} />
            ))}
          </List>
        </div>
      </div>
    </PullRefresh>
  );
}
